<template>
  <view class="container">
    <!-- 搜索框 -->
	<!-- <search tips="搜索商品" @event="$navTo('pages/search/index')" /> -->
	<view class="search">
		<view style="display: flex;align-items: center;justify-content: center; color: #82848A;width: 100%;height: 60rpx;"  v-if="!goSearch" @click="goSearch=true">
			<u-icon name="search"></u-icon>
			搜索
		</view>
		<u-input v-model="params.goodsName" @blur="goSearchChangeArr" v-if="goSearch" style="width: 80%;margin: auto;" placeholder="请输入关键词"  type="text" :border="false" />
	</view>
	<view class="content">
			<scroll-view scroll-y="true" class="leftBox">
				<view class="leftArr">
					<text @click="changeClassify(item.category_id)" :class="item.category_id == params.categoryId ? 'activeText':''" v-for="(item,index) in classifyArr" :key="index">{{item.name}}</text>
				</view>
			</scroll-view>
			<scroll-view scroll-y="true" class="rightBox" @scrolltolower="scrolltolower">
				<view class="rightArr">
					<view v-for="(item,index) in goodsArr" :key="index" class="arrItem">
						<image  class="cover" :src="item.goods_image" mode="aspectFit" @click="handleTargetGoods(item.goods_id)" ></image>
					
						<view class="desc" @click="handleTargetGoods(item.goods_id)" >
							<text >{{item.goods_name}}</text>
							<view class="rightContent">
								<text >￥{{item.goods_price}}</text>
								<!-- <image src="../../static/item11.png" mode="widthFix" @click.stop.prevent="addCar(item)"></image> -->
							</view>
						</view>
					</view>
				</view>
				<!-- <empty v-if="!goodsArr.length" :isLoading="isLoading" /> -->
				
			</scroll-view>
	</view>
	<view class="" v-if="false">
    <!-- 分类样式：一级分类(大图) 10 -->
    <view class="cate-content" v-if="templet.style == 10 && list.length > 0">
      <view class="cate-wrapper cate_style__10">
        <scroll-view :scroll-y="true" :style="{ height: `${scrollHeight - 10}px` }">
          <view class="cate-item" v-for="(item, index) in list" :key="index"
            @click="onTargetGoodsList(item.category_id)">
            <image v-if="item.image" mode="widthFix" :src="item.image.preview_url"></image>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 分类样式：一级分类(小图) 11 -->
    <view class="cate-content" v-else-if="templet.style == 11 && list.length > 0">
      <view class="cate-wrapper cate_style__11">
        <scroll-view class="clear" :scroll-y="true" :style="{ height: `${scrollHeight - 10}px` }">
          <view class="cate-item" v-for="(item, index) in list" :key="index"
            @click="onTargetGoodsList(item.category_id)">
            <image v-if="item.image" mode="widthFix" :src="item.image.preview_url"></image>
            <text class="f-26">{{ item.name }}</text>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 分类样式：二级分类 20 -->
    <view class="cate-content dis-flex" v-else-if="templet.style == 20 && list.length > 0">

      <!-- 左侧 一级分类 -->
      <scroll-view class="cate-left f-28" :scroll-y="true" :style="{ height: `${scrollHeight}px` }">
        <text class="type-nav" :class="{ selected: curIndex == index }" v-for="(item, index) in list" :key="index"
          @click="handleSelectNav(index)">{{ item.name }}</text>
      </scroll-view>

      <!-- 右侧 二级分类 -->
      <scroll-view class="cate-right b-f" :scroll-top="scrollTop" :scroll-y="true"
        :style="{ height: `${scrollHeight}px` }">
        <view v-if="list[curIndex]">
          <view class="cate-right-cont">
            <view class="cate-two-box">
              <view class="cate-cont-box">
                <view class="flex-three" v-for="(item, idx) in list[curIndex].children" :key="idx"
                  @click="onTargetGoodsList(item.category_id)">
                  <view class="cate-img">
                    <image v-if="item.image" :src="item.image.preview_url"></image>
                  </view>
                  <text>{{ item.name }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
		
	</view>
  </view>
</template>

<script>
  import { setCartTabBadge } from '@/utils/app'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import SettingModel from '@/common/model/Setting'
  import * as CategoryApi from '@/api/category'
  import * as UserApi from '@/api/user'
  import Search from '@/components/search'
  import Empty from '@/components/empty'

  // 最后一次刷新时间
  let lastRefreshTime;

  export default {
    components: {
      Search,
      Empty
    },
    data() {
      return {
		user: {},
        // 列表高度
        scrollHeight: 0,
        // 一级分类：指针
        curIndex: 0,
        // 内容区竖向滚动条位置
        scrollTop: 0,
        // 分类列表
        list: [],
        // 分类模板设置
        templet: {},
        // 正在加载中
        isLoading: true,
		classifyArr:[],
		params:{
			categoryId : '',
			is_grade: 2 ,
			is_grade_type : '',
			page: 1,
			limit: 6,
			goodsName: '',
			// sortPrice: '0',// 0 由低到高 1由高到底
			// sortType: 'all',
		},
		goodsArr:[],
		noMore : false,
		goSearch: false,
		searchKeyWord : '',
		classifyArr:[
			{
				text:'综合',
				id:'all',
			},
			{
				text:'价格',
				id:'sortPrice',
			},
			{
				text:'销量',
				id:'sales',
			},
		],
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(option) {
	  this.getClassify()
      // const app = this
      // 设置分类列表高度
      // app.setListHeight()
      // 加载页面数据
      // app.onRefreshPage()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 每间隔5分钟自动刷新一次页面数据
      // const curTime = new Date().getTime()
      // if ((curTime - lastRefreshTime) > 5 * 60 * 1000) {
      //   this.onRefreshPage()
      // }
	  this.Init()
    },
    methods: {
	  Init() {
			UserApi.info().then(res => {
				this.user = res.data.data.userInfo
				this.params.is_grade_type = res.data.data.userInfo.grade.grade_id
				this.getGoodsArr()
			})
		},
	  handleTargetGoods(goodsId) {
		  console.log(goodsId);
		  let userInfo = uni.getStorageSync('userInfo')
		  if(!userInfo){
			  console.log('需要授权登录');
			  this.commonGetwxCode()
			  return
		  }
		  if(this.params.is_grade_type != userInfo.grade.grade_id){
			  return  uni.showToast({
						title:'您的当前级别不能购买当前商品!',
						icon:'none',
						duration:3000,
					  })
		  }
		   this.$navTo('pages/goods/detail', { goodsId })
	  },
	  goSearchChangeArr(){
		if(this.params.goodsName){
			this.goodsArr = []
			this.params.page  = 1
			this.getGoodsArr()
		}else{
			this.goodsArr = []
			this.params.page  = 1
			this.params.goodsName = ''
			this.goSearch = false
			this.getGoodsArr()
		}  
	  },
	  async addCar(_item){
		  console.log(_item)
		  let data = {
			goodsId:_item.goods_id, 
			goodsNum:1,
			// goodsSkuId:_item.goods_no,
			goodsSkuId: 0 ,
			is_grade_type : this.params.is_grade_type,
		  }
		  await this.myhttp({
			  url:'?s=/api/cart/add',
			  data
		  }).then(res=>{
			  console.log(res);
			  if(res.data.status==200){
				  uni.showToast({
				  	title:'加入购物车成功!',
				  	icon:'success'
				  })
			  }else if(res.data.message){
				  uni.showToast({
				  	title:'你不能加入当前级别的商品!',
				  	icon:'none',
					duration:3000,
				  })
			  }else{
				  uni.showToast({
				  	title:'加入购物车失败!',
				  	icon:'none'
				  })
			  }
			  
		  }).catch(err=>{
			 
		  })
	  },
	  scrolltolower(){
		  if(this.noMore){
			  uni.showToast({
			  	title:'没有更多数据了!',
			  	icon:'none'
			  })
			  return
		  }else{
			this.params.page++
		  }
		  this.getGoodsArr()
	  },
	  changeClassify(_id){
		 this.params.categoryId  = _id
		 this.params.page  = 1
		 this.goodsArr = []
		 this.getGoodsArr()
	  },	
	  async getClassify(){
		await this.myhttp({
			url:'?s=/api/Category/list&page=1',
			data:{
				page : 1
			}
		}).then(res=>{
			let obj = {
				category_id : '',
				name : '全部'
			}
			if(res.data.status ==200){
				this.classifyArr = res.data.data.list
				this.classifyArr.unshift(obj)
			}
		})  
	  },
	  async getGoodsArr(){
	  		await this.myhttp({
	  			url:'?s=/api/Goods/list',
	  			data: this.params
	  		}).then(res=>{
	  			if(res.data.status ==200){
	  				let newArr = res.data.data.list.data
	  				this.goodsArr = [...this.goodsArr,...newArr]
					if(newArr.length < this.params.limit || res.data.data.list.total ==this.params.limit){
						this.noMore = true
					}else{
						this.noMore = false
					}
	  			}
	  		})  
	  },
      // 刷新页面
      onRefreshPage() {
        // 记录刷新时间
        lastRefreshTime = new Date().getTime()
        // 获取页面数据
        this.getPageData()
        // 更新购物车角标
        setCartTabBadge()
      },

      /**
       * 获取页面数据
       */
      getPageData() {
        const app = this
        app.isLoading = true
        Promise.all([
            // 获取分类模板设置
            // 优化建议: 可以将此处的false改为true 启用缓存
            SettingModel.data(false),
            // 获取分类列表
            CategoryApi.list()
          ])
          .then(result => {
            // 初始化分类模板设置
            app.initTemplet(result[0])
            // 初始化分类列表数据
            app.initCategory(result[1])
          })
          .finally(() => app.isLoading = false)
      },

      /**
       * 初始化分类模板设置
       * @param {Object} result
       */
      initTemplet(setting) {
        this.templet = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
      },

      /**
       * 初始化分类列表数据
       * @param {Object} result
       */
      initCategory(result) {
        const app = this
        const data = result.data
        app.list = data.list
      },

      /**
       * 设置分类列表高度
       */
      setListHeight() {
        const app = this
        uni.getSystemInfo({
          success(res) {
            app.scrollHeight = res.windowHeight - 47
          }
        })
      },

      // 一级分类：选中分类
      handleSelectNav(index) {
        const app = this
        app.curIndex = index
        app.scrollTop = 0
      },

      // 跳转至商品列表页
      onTargetGoodsList(categoryId) {
        this.$navTo('pages/goods/list', { categoryId })
      }

    },

    /**
     * 设置分享内容
     */
    onShareAppMessage() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    }

  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
.container{
	.search {
				height: 70rpx;
				// background: #FFFFFF;
				background: #f6f6f6;
				// box-shadow: 0px 1px 10px rgba(221, 221, 221, 0.5);
				border-radius: 35rpx;
				display: grid;
				place-items: center;
				margin: 0 20rpx 15rpx;
	}
	.content{
		display: flex;
		height: calc( 100vh - 95rpx ) ;
		width: 100%;
		border-top: 3rpx solid #EEEEEE;
		.leftBox{
			// background: pink;
			height: 100%;
			width: 190rpx;
			border-right: 3rpx solid #EEEEEE;
			.leftArr{
				display: flex;
				flex-direction: column;
				align-items: center;
				text{
					padding: 20rpx 0;
				}
				.activeText{
					background: #FFC243;
					width: 100%;
					display: grid;
					place-items: center;
				}
			}
		}
		.rightBox{
			height: 100%;
			width: calc( 100vw - 190rpx );
			.rightArr{
				display: flex;
				flex-direction: column;
				.arrItem{
					&:last-child{
						border-bottom: 0rpx solid #EEEEEE;
					}
					display: flex;
					align-items: center;
					height: 210rpx;
					border-bottom: 2rpx solid #EEEEEE;
					margin: 0rpx 15rpx;
					.cover{
						width: 180rpx;
						height: 180rpx;
					}
					.desc{
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: space-evenly;
						height: 100%;
						padding: 0 20rpx;
						text{
							color: #262626;
							font-size: 24rpx;
							font-weight: 600;
							text-overflow: -o-ellipsis-lastline;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							line-clamp: 2;
							-webkit-box-orient: vertical;
						}
						.rightContent{
							display: flex;
							justify-content: space-between;
							text{
								color: #E10000;
								font-size: 28rpx;
							}
							image{
								width: 50rpx;
							}
						}
					}
				}
			}
		}
	}
	
}
	
	
	
  .cate-content {
    background: #fff;
  }

  .cate-wrapper {
    padding: 0 20rpx 20rpx 20rpx;
    box-sizing: border-box;
  }

  /* 一级分类(大图) 10 */

  .cate_style__10 .cate-item {
    margin-bottom: 18rpx;
  }

  .cate_style__10 .cate-item:last-child {
    margin-bottom: 0;
  }

  .cate_style__10 .cate-item image {
    display: block;
    width: 100%;
    height: auto;
  }

  /* 一级分类(小图) 11 */

  .cate_style__11 .cate-item {
    float: left;
    padding: 25rpx;
    width: 33.3333%;
    text-align: center;
    box-sizing: border-box;
  }

  .cate_style__11 .cate-item image {
    /* height: 208.656rpx; */
    width: 100%;
    display: block;
  }

  .cate_style__11 .cate-item image {
    display: block;
    width: 100%;
    margin-bottom: 10rpx;
  }

  .cate_style__11 .cate-item text {
    display: block;
    color: #555;
  }

  /* 二级分类 20 */

  .cate-content {
    width: 100%;
  }

  .cate-left {
    flex-direction: column;
    display: flex;
    width: 200rpx;
    color: #444;
    height: 100%;
    background: #f8f8f8;
  }

  .cate-right {
    display: flex;
    flex-direction: column;
    width: 550rpx;
    height: 100%;
    overflow: hidden;
  }

  .cate-right-cont {
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    align-content: flex-start;
    padding-top: 26rpx;
  }

  .type-nav {
    position: relative;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    z-index: 10;
    display: block;
    font-size: 26rpx;
  }

  .type-nav.selected {
    background: #fff;
    color: #fa2209;
    border-right: none;
    font-size: 28rpx;
  }

  .cate-cont-box {
    margin-bottom: 30rpx;
    padding-bottom: 10rpx;
    background: #fff;
    overflow: hidden;
  }

  .cate-cont-box .cate-img {
    padding: 13rpx 10rpx 4rpx 10rpx;
  }

  .cate-cont-box .cate-img image {
    width: 100%;
    height: 150rpx;
    border-radius: 10rpx;
  }

  .cate-cont-box text {
    text-align: center;
    display: block;
    font-size: 26rpx;
    padding-bottom: 14rpx;
    color: #444;
    padding: 0 15rpx 30rpx 15rpx;
  }

  .cate-two-box {
    width: 100%;
    padding: 0 10px;
  }
</style>
